
package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.MessageType;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.core.util.WebChatUtil;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyEkbResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wxApi")
public class WxapiController extends BaseController {

    private static final Logger log= LoggerFactory.getLogger(WxapiController.class);
    @Resource
    private BtyBxdService btyBxdService;
    @Resource
    private BtyBxdaService btyBxdaService;
    @Resource
    private MeiTuanService meiTuanService;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private BtyArchivesService btyArchivesService;
    @Resource
    private WebChatService webChatService;
    @Resource
    private DeptService deptService;
    @Resource
    private TaskService taskService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private ProjectService projectService;
    @Resource
    private BtyWageService btyWageService;
    @Resource
    private UserService userService;
    @Resource
    private TaskFlowMapper taskFlowMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private TaskStatusMapper taskStatusMapper;
    @Resource
    private BtyTxlMapper btyTxlMapper;
    @Resource
    private BtyEkbService ekbService;

    private static final String TOKEN = "btyky";
    DecimalFormat format = new DecimalFormat("0.00");

    @RequestMapping("")
    private void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 开发者提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上，GET请求携带参数
            String signature = request.getParameter("signature");// 微信加密签名（token、timestamp、nonce。）
            String timestamp = request.getParameter("timestamp");// 时间戳
            String nonce = request.getParameter("nonce");// 随机数
            String echostr = request.getParameter("echostr");// 随机字符串
            // 将token、timestamp、nonce三个参数进行字典序排序
            String[] params = new String[]{TOKEN, timestamp, nonce};
            Arrays.sort(params);
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            String clearText = params[0] + params[1] + params[2];
            String algorithm = "SHA-1";
            String sign = new String(
                    Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true));
            // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if (signature.equals(sign)) {
                response.getWriter().print(echostr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO 消息的接收、处理、响应
        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名（token、timestamp、nonce。）
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");// 随机数
        //确认此次GET请求来自微信服务器，原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
        if (!WebChatUtil.checkSignature(signature, timestamp, nonce)) {
            //消息不可靠，直接返回
            response.getWriter().write("");
            return ;
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/xml");
            //调用parseXml方法解析请求消息
            Map<String, String> map = MessageType.parseXml(request, response);
            String MsgType = map.get("MsgType");
            String content = map.get("Content") == null ? "" : map.get("Content");
            String openid = map.get("FromUserName");
            StringBuilder sb = new StringBuilder();
//            Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
//            String accessToken = "";
//            if (ToolUtil.isNotEmpty(dict)) {
//                accessToken = dict.getName();
//            }
            int num = 0;
            int flag = 0;

            //查找可乐机负责人openID
            Long role = 1314488482857709570L;//可乐机负责人
            List<String> openidlist = userService.listOpenidsByRole(role);
            if(ToolUtil.isEmpty(openidlist)){
                log.error("未找到可乐机负责人微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            }
            log.info("=========可乐机负责人:" + openidlist + "========");

            //查找督导openID
            Long ddRole = 1283292980305018882L;//督导
            List<String> ddlist = userService.listOpenidsByRole(ddRole);
            if(ToolUtil.isEmpty(ddlist)){
                log.error("未找到督导微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            }
            log.info("=========督导:" + ddlist + "========");

            //查找营运经理openID
            Long yyRole = 1308249608428101633L;//营运经理
            List<String> yylist = userService.listOpenidsByRole(yyRole);
            if(ToolUtil.isEmpty(yylist)){
                log.error("未找到营运经理微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            }
            log.info("=========营运经理:" + yylist + "========");

            //获取姓名和银行卡号匹配供应商
            if (content.contains("#")) {
                String xm = content.split("[#]")[0].replaceAll("\\s*", "");
                //替换大部分空白字符,不限于空格
                String yhk = content.split("[#]")[1].replaceAll("\\s*", "");
                List<BtyBxda> bxdaList = btyBxdaService.list(new QueryWrapper<BtyBxda>().eq("xm", xm).eq("yhk", yhk));
                //绑定供应商的openid
                if (bxdaList.size() > 0) {
                    //绑定之前查询是否已经绑定
                    List<BtyBxda> bxdaLists = btyBxdaService.list(new QueryWrapper<BtyBxda>().eq("openid", openid));
                    if (bxdaLists.size() > 0) {
                        flag = 1;
                        btyBxdaService.setOpenid(openid, xm, yhk);
                    } else {
                        num = btyBxdaService.setOpenid(openid, xm, yhk);
                    }
                }
                // }
//            //通过openid获取昵称
//            emplate restTemplate = new RestTemplate();
//            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
//            //String url = "https://api.weixin.qq.com/cgi-bin/user/info";
//            String userInfo = restTemplate.getForObject(url, String.class);
//            JSONObject jsonObject = JSONObject.parseObject(userInfo);
//            if(ToolUtil.isNotEmpty(jsonObject)){
//               String nickName = jsonObject.get("nickname")==null?"":jsonObject.get("nickname").toString();
//               //保存openid和微信昵称
//               BtyWx btyWx1=btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid",openid));
//               if(ToolUtil.isEmpty(btyWx1)){
//                   BtyWx btyWx=new BtyWx();
//                   btyWx.setOpenid(openid);
//                   btyWx.setNickname(nickName);
//                   btyWxMapper.insert(btyWx);
//               }else{
//                   String nickname=btyWx1.getNickname();
//                   if(!nickname.equals(nickName)){
//                   btyWx1.setNickname(nickName);
//                   btyWxMapper.updateById(btyWx1);
//                   }
//               }
//            }
//            if(flag==1){
//
//            }
                if (num > 0) {
                    sb.append("绑定成功!请输入日期-日期查询例如20200801-20200805!");
                } else {
                    if (flag == 1) {
                        sb.append("已绑定成功,无须重复绑定!请输入日期-日期查询例如20200801-20200805!");
                    } else {
                        sb.append("绑定失败!姓名或者银行卡有误,请重新输入!");
                    }
                }
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }
            }
            else if (content.contains("部门")|content.contains("绑定部门")|content.contains("职级")|content.contains("绑定职级")) {
               sb.append("绑定部门或职级请输入 姓名@电话@部门或职级 例如：王五@158533@财务部   张三@15965512345@督导");
            }else if (content.contains("工资")|content.contains("查询工资")) {
               sb.append("查询工资请输入姓名gz身份证号 例如:张三gz12345");
            }
            //通过日期查询报销单相关数据
            else if (content.contains("-")) {
                String beginTime = content.split("[-]")[0].replaceAll("\\s*", "");
                String endTime = content.split("[-]")[1].replaceAll("\\s*", "");
                endTime = endTime + " 23:59:59";
                List<BtyBxd> listZje = btyBxdService.sumJe(openid, beginTime, endTime);
                List<BtyBxd> list = btyBxdService.sumZcje(openid, beginTime, endTime);
                List<BtyBxd> listWbx = btyBxdService.sumWbxje(openid, beginTime, endTime);
                if (ToolUtil.isNotEmpty(listZje)) {
                    String xm1 = listZje.get(0).getBxr();
                    String sumJe = format.format(new BigDecimal(listZje.get(0).getSumZcje()));
                    sb.append(xm1).append("总金额:").append(sumJe).append("\r\n");
                    if (ToolUtil.isNotEmpty(list)) {
                        String xm2 = list.get(0).getBxr();
                        String sumZcje = format.format(new BigDecimal(list.get(0).getSumZcje()));
                        String sumWbxje = listWbx == null | listWbx.size() == 0 ? "0" : format.format(new BigDecimal(listWbx.get(0).getSumZcje()));
                        sb.append(xm2).append("已报销:").append(sumZcje).append("\r\n");
                        sb.append(xm2).append("未报销:").append(sumWbxje).append("\r\n");
                        for (int i = 0; i < list.size(); i++) {
                            String dm = list.get(i).getDm();
                            //String xm=list.get(i).getBxr();
                            String zcje = format.format(new BigDecimal(list.get(i).getZcje()));
                            sb.append(dm).append("已报销金额:").append(zcje).append("\r\n");
                        }
                    } else {
                        sb.append(xm1).append("已报销:0").append("\r\n");
                    }

                    if (ToolUtil.isNotEmpty(listWbx)) {
                        for (int i = 0; i < listWbx.size(); i++) {
                            String dm = listWbx.get(i).getDm();
                            String zcje = listWbx.get(i).getZcje() == null ? "0" : format.format(new BigDecimal(listWbx.get(i).getZcje()));
                            sb.append(dm).append("未报销金额:").append(zcje).append("\r\n");
                        }
                    } else {
                        sb.append(xm1).append("未报销:0").append("\r\n");
                    }
                } else {
                    sb.append("暂无数据!");
                }

            }
            //通过日期查询易快报报销单相关数据  ～
            else if (content.contains("~")|content.contains("～")) {
                String beginTime = content.split("~|～")[0].replaceAll("\\s*", "");
                String endTime = content.split("~|～")[1].replaceAll("\\s*", "");
                endTime = endTime + " 23:59:59";
                List<BtyEkb> lists=ekbService.list(new QueryWrapper<BtyEkb>().eq("openid",openid));
                if(lists.size()<=0){
                    sb.append("请先绑定之后再查询!绑定格式 姓名*银行卡号 例如 张三*621700235000");
                }else {
                    String xm=lists.get(0).getFkr().replaceAll("\\s*", "");
                    String yhk=lists.get(0).getYhk().replaceAll("\\s*", "");
                    ekbService.setOpenid(openid, xm, yhk);

                    List<BtyEkbResult> listZje = ekbService.sumJe(openid, beginTime, endTime);
                    List<BtyEkbResult> list = ekbService.sumZcje(openid, beginTime, endTime);
                    List<BtyEkbResult> listWbx = ekbService.sumWbxje(openid, beginTime, endTime);
                    if (ToolUtil.isNotEmpty(listZje)) {
                        String xm1 = listZje.get(0).getFkr().replaceAll("\\s*", "");
                        String sumJe = format.format(new BigDecimal(listZje.get(0).getSumZcje()));
                        sb.append(xm1).append("总金额:").append(sumJe).append("\r\n");
                        if (ToolUtil.isNotEmpty(list)) {
                            String xm2 = list.get(0).getFkr().replaceAll("\\s*", "");
                            String sumZcje = format.format(new BigDecimal(list.get(0).getSumZcje()));
                            String sumWbxje = listWbx == null | listWbx.size() == 0 ? "0" : format.format(new BigDecimal(listWbx.get(0).getSumZcje()));
                            sb.append(xm2).append("已报销:").append(sumZcje).append("\r\n");
                            sb.append(xm2).append("未报销:").append(sumWbxje).append("\r\n");
                            for (int i = 0; i < list.size(); i++) {
                                String dm = list.get(i).getBm();
                                String zcje = format.format(list.get(i).getSumAmount() == null ? BigDecimal.ZERO : list.get(i).getSumAmount());
                                sb.append(dm).append("已报销金额:").append(zcje).append("\r\n");
                            }
                        } else {
                            sb.append(xm1).append("已报销:0").append("\r\n");
                        }

                        if (ToolUtil.isNotEmpty(listWbx)) {
                            for (int i = 0; i < listWbx.size(); i++) {
                                String dm = listWbx.get(i).getBm();
                                String zcje = format.format(listWbx.get(i).getSumAmount() == null ? BigDecimal.ZERO : listWbx.get(i).getSumAmount());
                                sb.append(dm).append("未报销金额:").append(zcje).append("\r\n");
                            }
                        } else {
                            sb.append(xm1).append("未报销:0").append("\r\n");
                        }
                    } else {
                        sb.append("暂无数据!");
                    }
                }
            }
            //通过门店号查询美团消费相关数据
            else if (content.contains("mt")) {
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
                String beginTime=df.format(new Date());
                String endTime = beginTime + " 23:59:59";
                //获取门店编号
                String yaoMa=content.substring(content.indexOf("mt")+2);
                List<MeiTuan>meiTuanList=meiTuanService.list(new QueryWrapper<MeiTuan>().eq("mm",yaoMa)
                .ge("sj",beginTime).le("sj",endTime));
                if (ToolUtil.isNotEmpty(meiTuanList)) {
                    for (int i = 0; i < meiTuanList.size(); i++) {
                        String xm = meiTuanList.get(i).getXm()==null?"":meiTuanList.get(i).getXm();
                        String phone = meiTuanList.get(i).getSjh();
                        String xf =meiTuanList.get(i).getXf()==null?"0":format.format(new BigDecimal(meiTuanList.get(i).getXf()));
                        sb.append(xm).append(phone).append("xf:").append(xf).append("\r\n");
                    }
                } else {
                    sb.append("暂无数据!");
                }
            }
            //通过姓名和银行卡号绑定易快报
            if (content.contains("*")) {
                String xm = content.split("[*]")[0].replaceAll("\\s*", "");
                //替换大部分空白字符,不限于空格
                String yhk = content.split("[*]")[1].replaceAll("\\s*", "");
                List<BtyEkb> bxdaList = ekbService.list(new QueryWrapper<BtyEkb>().eq("fkr", xm).eq("yhk", yhk));
                //绑定供应商的openid
                if (bxdaList.size() > 0) {
                    //绑定之前查询是否已经绑定
                    List<BtyEkb> bxdaLists = ekbService.list(new QueryWrapper<BtyEkb>().eq("openid", openid));
                    if (bxdaLists.size() > 0) {
                        flag = 1;
                    } else {
                        num = ekbService.setOpenid(openid, xm, yhk);
                    }
                }
                if (num > 0) {
                    sb.append("绑定成功!请输入日期~日期查询例如20200801~20200805!");
                } else {
                    if (flag == 1) {
                        sb.append("已绑定成功,无须重复绑定!请输入日期~日期查询例如20200801~20200805!");
                    } else {
                        sb.append("绑定失败!姓名或者银行卡有误,请重新输入!");
                    }
                }
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }
            }
            //查询工资前绑定openid
            else if (content.contains("bd")) {
                //获取姓名和身份证号
                String xm = content.substring(0, content.indexOf("bd")).replaceAll("\\s*", "");
                String sfz = content.substring(content.indexOf("bd") + 2).replaceAll("\\s*", "");
                //通过姓名和身份证查询是否在档案中存在
                BtyArchives btyArchives=btyArchivesService.getOne(new QueryWrapper<BtyArchives>()
                        .eq("xm",xm).eq("sfz",sfz));
                if(ToolUtil.isNotEmpty(btyArchives)){
                    //查询是否已经绑定
                    BtyArchives btyArchives1=btyArchivesService.getOne(new QueryWrapper<BtyArchives>().eq("openid",openid));
                    if (ToolUtil.isNotEmpty(btyArchives1)) {
                        flag = 1;
                    } else {
                        num = btyArchivesService.setOpenid(openid, xm, sfz);
                    }
                }
                if (num > 0) {
                    sb.append("绑定成功!查询工资请输入wage日期查询 例如 wage202009");
                } else {
                    if (flag == 1) {
                        sb.append("已绑定成功,无须重复绑定!查询工资请输入wage日期查询 例如 wage202009");
                    } else {
                        sb.append("绑定失败!姓名或者身份证号有误,请重新输入!");
                    }
                }
            }
            else if (content.contains("wage")) {
                //获取当前月的上个月
                String lastMonth = DateUtil.getLastMonth();
                //获取当前月的天数
                int days = DateUtil.getDaysOfMonth(lastMonth);
                int chuqts = days - 4;//26
                BigDecimal day = new BigDecimal(chuqts);
                //获取姓名和身份证号
                //String xm = content.substring(0, content.indexOf("wage")).replaceAll("\\s*", "");
                String month = content.substring(content.indexOf("wage") + 4).replaceAll("\\s*", "");

                if (ToolUtil.isEmpty(month)) {
                    sb.append("查询工资请输入wage月份 例如:wage202009");
                }
                else{
                    String sumWage = btyWageService.sumWages(openid,month);
                    if (ToolUtil.isEmpty(sumWage)) {
                        sumWage = "0";
                    }
                    List<BtyWage> wageList = btyWageService.wageLists(openid,month);
                    sumWage = format.format(new BigDecimal(sumWage));
                    if (ToolUtil.isNotEmpty(wageList)) {
                        String xm=wageList.get(0).getXm();
                        sb.append(xm).append("实发合计:").append(sumWage).append("\r\n");
                        for (int i = 0; i < wageList.size(); i++) {
                            String dm = wageList.get(i).getDm();
                            String cqts = wageList.get(i).getCqts() == null ? "0" : format.format(new BigDecimal(wageList.get(i).getCqts()));
                            BigDecimal day1 = new BigDecimal(cqts);
                            //实际出勤天数大于等于每月出勤天数
                            if (day1.compareTo(day) > -1) {
                                cqts = day.toString();
                            }
                            String sfgz = wageList.get(i).getSfhj() == null ? "0" : format.format(new BigDecimal(wageList.get(i).getSfhj()));
                            //sb.append(xm).append(dm).append("实发:").append(sfgz).append("\r\n");
                            sb.append(dm).append("出勤:").append(cqts).append("实发:").append(sfgz).append("\r\n");
                        }
                    } else {
                        sb.append("暂无数据!");
                    }
                }
            }
            //通过姓名和身份证获取上月工资
            else if (content.contains("gz")) {
                //获取当前月的上个月
                String lastMonth = DateUtil.getLastMonth();
                //获取当前月的天数
                int days = DateUtil.getDaysOfMonth(lastMonth);
                int chuqts = days - 4;//26
                BigDecimal day = new BigDecimal(chuqts);
                //获取姓名和身份证号
                String xm = content.substring(0, content.indexOf("gz")).replaceAll("\\s*", "");
                String sfz = content.substring(content.indexOf("gz") + 2).replaceAll("\\s*", "");

                if (ToolUtil.isEmpty(sfz)|ToolUtil.isEmpty(xm)) {
                    sb.append("请输入姓名gz身份证号 例如:张三gz12345");
                }
                else{
                String sumWage = btyWageService.sumWage(lastMonth, xm, sfz);
                if (ToolUtil.isEmpty(sumWage)) {
                    sumWage = "0";
                }


                List<BtyWage> wageList = btyWageService.wageList(lastMonth, xm, sfz);
                sumWage = format.format(new BigDecimal(sumWage));
                if (ToolUtil.isNotEmpty(wageList)) {
                    sb.append(xm).append("实发合计:").append(sumWage).append("\r\n");
                    for (int i = 0; i < wageList.size(); i++) {
                        String dm = wageList.get(i).getDm();
                        String cqts = wageList.get(i).getCqts() == null ? "0" : format.format(new BigDecimal(wageList.get(i).getCqts()));
                        BigDecimal day1 = new BigDecimal(cqts);
                        //实际出勤天数大于等于每月出勤天数
                        if (day1.compareTo(day) > -1) {
                            cqts = day.toString();
                        }
                        String sfgz = wageList.get(i).getSfhj() == null ? "0" : format.format(new BigDecimal(wageList.get(i).getSfhj()));
                        //sb.append(xm).append(dm).append("实发:").append(sfgz).append("\r\n");
                        sb.append(dm).append("出勤:").append(cqts).append("实发:").append(sfgz).append("\r\n");
                    }
                } else {
                    sb.append("暂无数据!");
                }
             }
            }
            //通过姓名和手机号绑定钉钉id
//            else if (content.contains("*")) {
//                String xm = content.split("[*]")[0].replaceAll("\\s*", "");
//                //替换大部分空白字符,不限于空格
//                String phone = content.split("[*]")[1].replaceAll("\\s*", "");
//                List<BtyArchives> btyArchivesList = btyArchivesService.list(new QueryWrapper<BtyArchives>().eq("xm", xm).eq("tel", phone));
////                //绑定用户的钉钉id
//                if (btyArchivesList.size() > 0) {
//                    //绑定之前查询是否已经绑定
//                    List<BtyWx> wxList = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid));
//                    if (wxList.size() > 0) {
//                        List<BtyWx> wxLists = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid).eq("phone", phone));
//                        if (wxLists.size() > 0) {
//                            flag = 2;
//                        } else {
//                            BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
//                            btyWx.setPhone(phone);
//                            btyWx.setDingId(btyArchivesList.get(0).getBh());
//                            btyWx.setName(btyArchivesList.get(0).getXm());
//                            btyWx.setShopName(btyArchivesList.get(0).getDm());
//                            btyWx.setRegionOne(btyArchivesList.get(0).getQy());
//                            btyWx.setRegionTwo(btyArchivesList.get(0).getEqy());
//                            btyWx.setPost(btyArchivesList.get(0).getZw());
//                            btyWxMapper.updateById(btyWx);
//                            num = 3;
//                        }
//                    } else {
//                        BtyWx btyWx = new BtyWx();
//                        btyWx.setOpenid(openid);
//                        btyWx.setId(UUIDUtils.getId());
//                        btyWx.setPhone(phone);
//                        btyWx.setDingId(btyArchivesList.get(0).getBh());
//                        btyWx.setName(btyArchivesList.get(0).getXm());
//                        btyWx.setShopName(btyArchivesList.get(0).getDm());
//                        btyWx.setRegionOne(btyArchivesList.get(0).getQy());
//                        btyWx.setRegionTwo(btyArchivesList.get(0).getEqy());
//                        btyWx.setPost(btyArchivesList.get(0).getZw());
//                        num = btyWxMapper.insert(btyWx);
//                    }
//                }
//                if (num > 0) {
//                    //通过openid获取姓名
//                    BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
//                    String name = "";
//                    if (ToolUtil.isNotEmpty(btyWx)) {
//                        name = btyWx.getName();
//                    }
//                    sb.append("绑定成功!欢迎" + name + "回家!【半天妖】*^_^*");
//                } else {
//                    if (flag == 2) {
//                        sb.append("已绑定成功,无须重复绑定!");
//                    } else {
//                        sb.append("绑定失败!姓名或者手机号有误,请重新输入!");
//                    }
//                }
//                if (ToolUtil.isEmpty(sb.toString())) {
//                    sb.append("您好!");
//                }
//
//            }
            //通过姓名和手机号，部门绑定部门
            else if (content.contains("@")) {
                String xm = content.split("[@]")[0].replaceAll("\\s*", "");
                //替换大部分空白字符,不限于空格
                String phone = content.split("[@]")[1].replaceAll("\\s*", "");
                //通过姓名和电话查询此人是否在档案表中存在
//                List<BtyArchives> archivesList = btyArchivesService.list(new QueryWrapper<BtyArchives>().eq("xm", xm)
//                        .eq("tel", phone));
//                if (ToolUtil.isEmpty(archivesList)) {
//                    sb.append("此人在档案中不存在,不允许绑定！");
//                }else{
                String bm = content.split("[@]")[2].replaceAll("\\s*", "");
                //查询部门是否存在
                Long deptId = null;
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("simple_name", bm));
                Long yyb=2009281147418640000L;
                Long dd=2009290127271020000L;
                Long yyjl=2010190923009120000L;
                if (ToolUtil.isNotEmpty(dept)) {
                    deptId = dept.getDeptId();
                    if (deptId.longValue()==yyb.longValue()| deptId.longValue()==dd.longValue() | deptId.longValue()==yyjl.longValue()) {
                        //通过姓名和电话查询此人是否在档案表中存在
                        List<BtyArchives> archivesList = btyArchivesService.list(new QueryWrapper<BtyArchives>().eq("xm", xm)
                                .eq("tel", phone));
                        if (ToolUtil.isEmpty(archivesList)) {
                            sb.append("此手机号在档案中不存在,不允许绑定!");
                        }
                        else{
                            //绑定之前查询是否已经绑定
                            List<BtyWx> wxList = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid));
                            if (wxList.size() > 0) {
                                List<BtyWx> wxLists = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid).eq("phone", phone)
                                        .eq("name", xm).eq("dept_id", deptId));
                                if (wxLists.size() > 0) {
                                    flag = 2;
                                } else {
                                    BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                                    btyWx.setPhone(phone);
                                    btyWx.setName(xm);
                                    btyWx.setDeptId(deptId);
                                    btyWxMapper.updateById(btyWx);
                                    num = 3;
                                }
                            } else {
                                BtyWx btyWx = new BtyWx();
                                btyWx.setOpenid(openid);
                                btyWx.setId(UUIDUtils.getId());
                                btyWx.setPhone(phone);
                                btyWx.setName(xm);
                                btyWx.setDeptId(deptId);
                                num = btyWxMapper.insert(btyWx);
                            }
                            if (num > 0) {
                                BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                                String name = "";
                                if (ToolUtil.isNotEmpty(btyWx)) {
                                    name = btyWx.getName();
                                }
                                sb.append("绑定成功!欢迎" + name + "回家!【半天妖】*^_^*");
                            } else {
                                if (flag == 2) {
                                    sb.append("已绑定成功,无须重复绑定!");
                                } else {
                                    sb.append("绑定失败!姓名或者手机号有误,请重新输入!");
                                }
                            }
                            if (ToolUtil.isEmpty(sb.toString())) {
                                sb.append("您好!");
                            }
                        }
                    }
                    else{
                    //绑定之前查询是否已经绑定
                    List<BtyWx> wxList = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid));
                    if (wxList.size() > 0) {
                        List<BtyWx> wxLists = btyWxMapper.selectList(new QueryWrapper<BtyWx>().eq("openid", openid).eq("phone", phone)
                                .eq("name", xm).eq("dept_id", deptId));
                        if (wxLists.size() > 0) {
                            flag = 2;
                        } else {
                            BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                            btyWx.setPhone(phone);
                            btyWx.setName(xm);
                            btyWx.setDeptId(deptId);
                            btyWxMapper.updateById(btyWx);
                            num = 3;
                        }
                    } else {
                        BtyWx btyWx = new BtyWx();
                        btyWx.setOpenid(openid);
                        btyWx.setId(UUIDUtils.getId());
                        btyWx.setPhone(phone);
                        btyWx.setName(xm);
                        btyWx.setDeptId(deptId);
                        num = btyWxMapper.insert(btyWx);
                    }
                    if (num > 0) {
                        BtyWx btyWx = btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                        String name = "";
                        if (ToolUtil.isNotEmpty(btyWx)) {
                            name = btyWx.getName();
                        }
                        sb.append("绑定成功!欢迎" + name + "回家!【半天妖】*^_^*");
                    } else {
                        if (flag == 2) {
                            sb.append("已绑定成功,无须重复绑定!");
                        } else {
                            sb.append("绑定失败!姓名或者手机号有误,请重新输入!");
                        }
                    }
                    if (ToolUtil.isEmpty(sb.toString())) {
                        sb.append("您好!");
                    }
                  }
                } else {
                    sb.append("请输入正确的部门,部门名称只能为：技术部,财务部,人事部,开发部,工程部,培训部,拓展部,服务部,营运部,总经理,督导,营运经理,品牌营销中心,供应链部其中的一个\r\n " +
                            "例如：流星@13567@营运部\r\n");
//                    dept = new Dept();
//                    dept.setDeptId(UUIDUtils.getId());
//                    dept.setPid(24L);
//                    dept.setPids("[0],[24],");
//                    dept.setSimpleName(bm);
//                    Boolean flags = deptService.save(dept);
//                    if (flags == true) {
//                        deptId = dept.getDeptId();
//                    }
                }
            }


            //通过发送人openID和店名,确定可乐机安装状态
//            else if (openid.equals("oM18PwWQsdIP3QEKcWejL1tF3X8s") && content.contains("已完成")) {
            else if (openidlist.contains(openid) && content.contains("已完成")) {

                String name = content.split("已完成")[0].replaceAll("\\s*", "");
                //根据店名查询ProID
                Integer proId = taskService.selectProId(name);

                //查询可乐机到店安装任务是否已存在
                int count = taskMapper.selectCoke(proId,19,"可乐机安装完成");
                if (count == 0) {

                    //任务状态表
                    TaskStatus status = new TaskStatus();
                    status.setProId(proId);
                    status.setStatus(1);
                    status.setTaskId(19);
                    status.setTaskName("可乐机");
                    status.setContent("可乐机安装完成");

                    //流程明细表
                    TaskFlow taskFlow = new TaskFlow();
                    taskFlow.setProId(proId);
                    taskFlow.setTaskId(19);
                    taskFlow.setTaskName("可乐机");
                    taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
//                    taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
                    taskFlow.setCreateTime(new Date());

                    //新增任务相关表数据
                    num = taskFlowMapper.add(taskFlow);//新增flow表
                    int n = taskStatusMapper.updateStatus(status);
                    if (num > 0){
                        sb.append("提交成功! ");
                    }

/////////////////////
                    //向督导,营运经理,营运总监推送消息
                    String[] str = {"可乐机状态","可乐机", DateUtil.getNow(),name + "可乐机已安装"};
                    //发送模板
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(name,null, str);

                    Map<String, String> openidMap = projectService.selectDd(proId);
                    //督导
                    String dd = openidMap.get("dd");
                    //营运经理
                    String yyjl = openidMap.get("yyjl");
                    log.info("=======督导:"+ dd + "营运经理:" + yyjl + "=========");

//                    //督导
//                    String dd = "oM18PwaEw3B6OxaeDvkWeOxi6EGY";
//                    //营运经理
//                    String yyjl = "oM18Pwbpv4XqhwuvzVMYbU450DTs";


                    Long role_yyzj = 1305422678196678657L;//营运总监
                    List<String> list = userService.listOpenidsByRole(role_yyzj);

                    if(ToolUtil.isNotEmpty(list)){
                        log.info("=========营运总监:" + list + "========");

                        list.add(dd);
                        list.add(yyjl);
                        String[] openids = list.toArray(new String[list.size()]);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids,BusConst.MSURL,tempObj);
                        log.info("=======督导,营运经理,营运总监推送可乐机消息===========");
                    }
//                    //营运总监
//                    String yyzj = "oM18PwWDuSXALBEu7Y_YmdO8-tVw";
//                    String[] openids = new String[]{dd, yyjl, yyzj,BusConst.ITZJ};




////////////////////

                    num = 2;
                    if (num > 0){
                        sb.append(name + "可乐机安装完成,*^_^*");
                    }

                }else {
                    sb.append(name + "已提交,无需重复提交!");
                }

            }

            //通过发送人openID和店名,确定收银系统安装状态
            //刘书伟
            else if (openid.equals(BusConst.LSW) && content.contains("已确认")) {
//            else if (openid.equals("oM18PwWQsdIP3QEKcWejL1tF3X8s") && content.contains("已确认")) {

                String name = content.split("已确认")[0].replaceAll("\\s*", "");
                //根据店名查询ProID
                Integer proId = taskService.selectProId(name);

                //查询收银系统任务是否已存在
                int count = taskService.selectCount(proId, 21);
                if (count == 0) {

                    //任务状态表
                    TaskStatus status = new TaskStatus();
                    status.setProId(proId);
                    status.setStatus(0);
                    status.setTaskId(21);//收银系统
                    status.setTaskName("收银系统");
                    status.setContent("收银账号已建完，收银档案未建完");

                    //流程明细表
                    TaskFlow taskFlow = new TaskFlow();
                    taskFlow.setProId(proId);
                    taskFlow.setTaskId(21);
                    taskFlow.setTaskName("收银系统");
                    taskFlow.setStatus(0);//1提交；2审核未通过；3审核通过
//                    taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
                    taskFlow.setCreateTime(new Date());

                    //新增任务相关表数据
                    num = taskService.insertRent(status, taskFlow);

                    if (num > 0){
                        sb.append("提交成功!" + name +"收银账号已建完,*^_^*");
                    }

                    //通知档案负责人
                    String now = DateUtil.getNow();//当前时间
                    //查询店名
                    String dm = taskMapper.selectDm(status.getProId());
                    String data = dm + "收银账号已建完";

                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "收银账号已建完", "收银账号已建完", now, data);

                    String[] openids = new String[]{"oM18PwWQsdIP3QEKcWejL1tF3X8s"};

                    //推送消息
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    log.info("======已推送档案负责人收银账号已建完消息======");

                }else {
                    sb.append(name + "已确认,无需重复确认!");
                }

            }
            //通过发送人openID和店名,确定收银系统档案状态
            else if (openid.equals("oM18PwWQsdIP3QEKcWejL1tF3X8s") && content.contains("已确认")){

                String name = content.split("已确认")[0].replaceAll("\\s*", "");
                //根据店名查询ProID
                Integer proId = taskService.selectProId(name);

                //查询收银系统任务是否已存在
                int count = taskMapper.selectCoke(proId, 21,"收银档案已建完");
                if (count == 0) {

                    //任务状态表
                    TaskStatus status = new TaskStatus();
                    status.setProId(proId);
                    status.setStatus(1);
                    status.setTaskId(21);//收银系统
                    status.setTaskName("收银系统");
                    status.setContent("收银档案已建完");

                    //流程明细表
                    TaskFlow taskFlow = new TaskFlow();
                    taskFlow.setProId(proId);
                    taskFlow.setTaskId(21);
                    taskFlow.setTaskName("收银系统");
                    taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
//                    taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
                    taskFlow.setCreateTime(new Date());

                    //新增任务相关表数据
//                    num = taskService.insertRent(status, taskFlow);

                    //新增任务相关表数据
                    num = taskFlowMapper.add(taskFlow);//新增flow表
                    int n = taskStatusMapper.updateStatus(status);

                    if (num > 0){
                        sb.append("提交成功!" + name +"收银档案已确认,*^_^*");
                    }

                    //通知督导,设计
                    String now = DateUtil.getNow();//当前时间
                    //查询店名
                    String dm = taskMapper.selectDm(status.getProId());
                    String data = dm + "收银档案已建完";

                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "收银档案已建完", "收银档案已建完", now, data);

                    Map<String, String> openidMap = projectService.selectDd(proId);
                    //督导
                    String dd = openidMap.get("dd");

                    //设计(任召栋),督导
                    String[] openids = new String[]{BusConst.SJ, dd};

                    //推送消息
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    log.info("======已推送督导收银档案已建完消息======");

                }else {
                    sb.append(name + "已确认,无需重复确认!");
                }

            }
            //通过发送人openID和店名,修改店长,联系方式(督导修改)
            else if (ddlist.contains(openid) && content.contains("店长:")) {

                //店名
                String name = content.split("店长:")[0].replaceAll("\\s*", "");
                //店长
                String fzr = content.split("店长:")[1].replaceAll("\\s*", "");

                BtyTxlRY btyTxlRY = new BtyTxlRY();
                btyTxlRY.setFzr(fzr);
                btyTxlRY.setSsctdm(name);

                //根据店名修改负责人
                num = btyTxlMapper.updateBtyTxlRy(btyTxlRY);
                if (num > 0){
                    sb.append("提交成功! ");
                }
            }
            //通过发送人openID和店名,修改店长,联系方式(督导修改)
            else if (ddlist.contains(openid) && content.contains("联系方式:")) {

                //店名
                String name = content.split("联系方式:")[0].replaceAll("\\s*", "");
                //联系方式
                String lxfs = content.split("联系方式:")[1].replaceAll("\\s*", "");

                BtyTxlRY btyTxlRY = new BtyTxlRY();
                btyTxlRY.setLxfs(lxfs);
                btyTxlRY.setSsctdm(name);

                //根据店名修改联系方式
                num = btyTxlMapper.updateBtyTxlRy(btyTxlRY);
                if (num > 0){
                    sb.append("提交成功! ");
                }
            }
            //通过发送人openID和店名,修改食品经营许可证截止日期(营运经理修改)
            else if (yylist.contains(openid) && content.contains("食品经营许可证截止日期:")) {

                //店名
                String name = content.split("食品经营许可证截止日期:")[0].replaceAll("\\s*", "");
                //日期
                String date = content.split("食品经营许可证截止日期:")[1].replaceAll("\\s*", "");

                BtyTxl btyTxl = new BtyTxl();
                btyTxl.setDm(name);
                btyTxl.setSpjyxk(date);

                //根据店名修改食品经营许可证截止日期
                num = btyTxlMapper.updateBtyTxl(btyTxl);

                if (num > 0){
                    sb.append("修改成功! ");
                }
            }
            //TODO 工程账号注册
            else if(content.contains("工程账号注册")){
                String registrationInfo="工程账号注册请回复内容，格式如下:\r\n" +
                        "gczhzc，账号名称，姓名，密码，密码，手机号，角色名称\r\n" +
                        "(例如：gczhzc，半天妖真好吃，张三，111111，111111，17865768001，营运总监)\r\n" +
                        "注意：1.角色名称只能为：开发人员,开发总监,工程总监,营运总监,营运经理,督导,网上建店负责人,工程部，供应链，店长，其中的一个\r\n"+
                        "2.密码必须6到12位，且不能出现空格\r\n"+
                        "请牢记账号信息";
                sb.append(registrationInfo);
            }
            else if(content.contains("gczhzc")){
                log.info("工程账号注册，用户提交的注册账号信息为：{}",content);
                ResponseData data=userService.createUserAndSetRole(content);
                String registraResult =data.getMessage();
                sb.append(registraResult);
                log.info("工程账号注册， 注册结果：{}，注册信息：{}",registraResult,content);
            }
            //TODO 工程账号信息修改
            else if(content.contains("工程账号修改")){
                String registrationInfo="工程账号修改请按以下提示操作，格式如下:\r\n" +
                        "1.修改工程账号密码请发送：gczhxgmm，账号名称，旧密码，新密码，新密码\r\n" +
                        "注意：密码必须6到12位，且不能出现空格\r\n"+
                        "2.修改工程账号手机号请发送：gczhxgsjh，账号名称，新手机号\r\n" +
                        "3.修改工程账号角色请发送：gczhxgjs,账号名称，角色名称\r\n" +
                        "注意：角色名称只能为：开发人员,开发总监,工程总监,营运总监,营运经理,督导,网上建店负责人,工程部，供应链，店长，其中的一个";
                sb.append(registrationInfo);
            }
            else if(content.contains("gczhxg")){
                log.info("工程账号修改，用户提交的修改信息为：{}",content);
                String changeResult = userService.changeAccountInfo(content);
                sb.append(changeResult);
                log.info("工程账号修改，修改结果：{}，用户提交的修改信息为：{}",changeResult,content);
            }

            else {
                if (ToolUtil.isEmpty(sb.toString())) {
                    sb.append("您好!");
                }
            }


            String xml = "";//处理输入消息，返回结果的xml
            if (MessageType.REQ_MESSAGE_TYPE_EVENT.equals(MsgType)) {
                xml = webChatService.parseEvent(map);
            } else {
                xml = webChatService.parseMessage(map, sb.toString());
            }
            //返回封装的xml
            //System.out.println(xml);
            response.getWriter().write(xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}


